# coding:utf-8

from . import api
from ihome.utils.commons import login_required
from ihome.models import Order, User, UserToStudent, House
from flask import g, current_app, jsonify, request
from ihome.utils.response_code import RET
from alipay import AliPay
from ihome import constants, db

import os


@api.route("/order/save_data", methods=["POST"])
@login_required
def save_data():
    order_data = request.get_json()
    order_id = order_data.get("order_id")
    contract_img = order_data.get("contract_image")
    lease_month = order_data.get("pay_month")
    deposit = order_data.get("deposit")

    if not all([order_id, contract_img, lease_month, deposit]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    try:
        Order.query.filter_by(id=order_id).update({"contract_image": contract_img, "lease_month": lease_month,
                                                   "deposit": deposit})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")


@api.route("/order/<int:order_id>/payment", methods=["POST"])
@login_required
def order_pay(order_id):
    """发起支付宝支付、"""
    user_id = g.user_id
    all_money = request.get_json().get("all_money")

    # 判断用户是否是学生用户 是的话打八折
    try:
        user = UserToStudent.query.filter(UserToStudent.user_id == user_id).first();
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")
    if user is not None:
        all_money *= 0.8
    # 判断订单状态
    try:
        order = Order.query.filter(Order.id == order_id, Order.user_id == user_id, Order.status == "WAIT_PAYMENT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if order is None:
        return jsonify(errno=RET.NODATA, errmsg="订单数据有误")

    # print(os.path.join(os.path.dirname(__file__), "keys\\app_private_key.pem"))
    app_private_key_string = open(os.path.join(os.path.dirname(__file__), "keys/app_private_key.pem")).read()
    alipay_public_key_string = open(os.path.join(os.path.dirname(__file__), "keys/alipay_public_key.pem")).read()
    # 创建支付宝sdk的工具对象
    alipay_client = AliPay(
        appid="2016102000727176",
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,  # 私钥
        alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默认False
    )

    # 手机网站支付，需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
    order_string = alipay_client.api_alipay_trade_wap_pay(
        out_trade_no=order.id,  # 订单编号
        total_amount=str(all_money),   # 总金额
        subject=u"苦瓜房源网，订单编号 %s" % order.id,  # 订单标题
        return_url="http://127.0.0.1/#/mine/house_order/pay_result",  # 返回的连接地址
        notify_url=None  # 可选, 不填则使用默认notify url
    )

    # 构建让用户跳转的支付连接地址
    pay_url = constants.ALIPAY_URL_PREFIX + order_string
    return jsonify(errno=RET.OK, errmsg="OK", data={"pay_url": pay_url})


@api.route("/order/payment", methods=["PUT"])
@login_required
def save_order_payment_result():
    """保存订单支付结果"""
    user_id = g.user_id
    alipay_dict = request.get_json().get("dict")
    # alipay_dict = request.form.to_dict()
    # 对支付宝的数据进行分离  提取出支付宝的签名参数sign 和剩下的其他数据
    alipay_sign = alipay_dict.pop("sign")

    app_private_key_string = open(os.path.join(os.path.dirname(__file__), "keys\\app_private_key.pem")).read()
    alipay_public_key_string = open(os.path.join(os.path.dirname(__file__), "keys\\alipay_public_key.pem")).read()
    # 创建支付宝sdk的工具对象
    alipay_client = AliPay(
        appid="2016102000727176",
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,  # 私钥
        alipay_public_key_string=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默认False
    )

    # 借助工具验证参数的合法性
    # 如果确定参数是支付宝的，返回True，否则返回false
    result = alipay_client.verify(alipay_dict, alipay_sign)

    if result:
        # 修改数据库的订单状态信息，房屋状态信息
        order_id = alipay_dict.get("out_trade_no")
        trade_no = alipay_dict.get("trade_no")  # 支付宝的交易号
        total_amount = float(alipay_dict.get("total_amount")) # 订单支付总金额
        get_integral = total_amount/10
        try:
            order = Order.query.filter_by(id=order_id).first()
            Order.query.filter_by(id=order_id).update({"status": "WAIT_COMMENT", "trade_no": trade_no,
                                                       "amount": total_amount})
            House.query.filter_by(id=order.house_id).update({"house_status":"出租中"})
            User.query.filter_by(id=user_id).update({"integral":User.integral + get_integral})
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DATAERR, errmsg="保存失败")

    return jsonify(errno=RET.OK, errmsg="OK")








